package server;

import mapper.Mapper;

import java.io.InputStream;
import java.net.Socket;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String requestUrl = request.getRequestUrl();

            // 可能由于 chrome 的原因，浏览器会发一个无关的http请求，这个请求的url是 /favicon.ico，这里忽略掉它
            if (requestUrl.contains("favicon.ico")) {
                socket.close();
                return;
            }

            HttpServlet handler = mapper.getHandler(request.getHostName(), requestUrl);

            // 静态资源处理
            if (handler == null) {
                response.outputHtml(request.getRequestUrl());
            } else {
                // 动态资源servlet请求
                handler.service(request, response);
            }

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
